<?php

namespace app\api\controller\paotui;

use addons\paotui\library\BaiduApi\AipNlp;
use addons\paotui\library\Map;
use addons\paotui\service\Config as PaotuiConfig;
use app\admin\model\paotui\Config;
use app\admin\model\paotui\GoodsType;
use app\admin\model\paotui\TemplateIds;
use app\admin\model\paotui\Times;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;

use EasyWeChat\Factory;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['nlp_address','get_template_ids','regions','get_poi_nearby','decryptData','times','goods_type','getBPrice'];
    protected $noNeedRight = '*';

    /**
     * 获取当前开通城市
     */
    public function city(){
        $this->success("请求成功",PaotuiConfig::get('city'));
    }

    /**
     * 获取模板消息ID
     */
    public function get_template_ids(){
        $code = $this->request->post("code","");
        if(empty($code)){
            $this->success('请求成功',[]);
        }

        $templateIdsModel = new TemplateIds();
        $templateIdsList = $templateIdsModel->where(['code'=>['in',explode(",",$code)]])->column("template_id");

        $this->success('请求成功',$templateIdsList);
    }

    /**
     * 获取保价金额
     */
    public function getBPrice(){
        $b_price = $this->request->post("b_price");
        $postService = new \addons\paotui\service\Post();

        $this->success("请求成功",$postService->getBPrice($b_price));
    }


    /**
     * 小程序解码
     */
    public function decryptData(){

        $configModel = new Config();
        $config = $configModel->where(['group'=>'mini'])->column("name,value");

        $encryptedData = $this->request->request('encryptedData');
        $iv = $this->request->request('iv');
        $code = $this->request->request("code");

        $options = [
            'app_id'   => $config['mini_appid'],
            'secret'   => $config['mini_appsecret'],
        ];

        $app = Factory::miniProgram($options);
        $sns = $app->auth->session($code);

        if(!empty($sns['session_key'])){
            $data = $app->encryptor->decryptData($sns['session_key'],$iv,$encryptedData);
            $this->success("请求成功",$data);
        }else{
            $this->success("请求失败");
        }
    }

    /**
     * 获取预约时间段
     * type 1帮取、帮送
     */
    public function times(){
        $type = $this->request->post("type",1);

        $times = new Times();
        $timesList = $times->where(['type'=>$type])->order("weigh asc")->column("times");
        foreach ($timesList as &$v){
            $v = str_replace(" ","",$v);
        }
        $this->success("请求成功",$timesList);
    }

    /**
     *物品类型
     */
    public function goods_type(){
        $goodsTypeModel = new GoodsType();
        $goodsType = $goodsTypeModel->order("weigh asc")->column('goods_type');

        $this->success('请求成功',$goodsType);
    }


    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }

        $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
    }

    /**
     * 智能识别地址
     */
    public function nlp_address(){

        $content = $this->request->post("content");

        $content = str_replace(array("\r\n", "\r", "\n"), " ", $content);

        $configModel = new Config();
        $config = $configModel->where(['group'=>'base'])->column("name,value");

        $appid = $config['bd_appid'];
        $api_key = $config['bd_api_key'];
        $secret_key = $config['bd_secret_key'];

        if(strpos($content,$config['city']) === false){
            $content = str_replace("/",'',$config['city']).$content;
        }

        $client = new AipNlp($appid, $api_key, $secret_key);
        $address = $client->address($content);

        if(!empty($address['city'])){
            $address['province'] = str_replace('北京市',"北京",$address['province']);
            $address['province'] = str_replace('天津市',"天津",$address['province']);
            $address['province'] = str_replace('上海市',"上海",$address['province']);
            $address['province'] = str_replace('重庆市',"重庆",$address['province']);
        }

        $this->success('请求成功',$address);
    }

}
